//
//  ST_TianDailyTaskController.swift
//  btvideo
//
//  Created by Jason on 2021/10/27.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import RxCocoa
import RxSwift
import RxDataSources
import NSObject_Rx
import SwiftyJSON
import MJRefresh
import SwiftyUserDefaults


class ST_TianDailyTaskController: UICollectionViewController,ST_VMControllerLightNavBarProduce {
    
    lazy var tain_navigation_bar:ST_TIANLightNavigationBar = {
        let c = ST_TIANLightNavigationBar()
        c.title_nav_btn.setTitleForAllStates("任务")
        return c
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        request()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        defer{
            layout_navigation_bar()
        }
        
        configure_collection_view()
        
        binding()
    }
    
    private func configure_collection_view(){
        
         
        collectionView.backgroundColor = .white
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        collectionView.contentInset = UIEdgeInsets(top: statusBarHeight+44, left: 0, bottom: BTSafeAreaBottom + 10, right: 0)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.refreshControl = UIRefreshControl()
        
        
        collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_TianDailyTaskSectionReusableView.self)
        collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_TianDailyTaskBannerSectionReusableView.self)
        collectionView.register(cellWithClass: ST_TianDailyTaskCell.self)
        
    }
    
    
    func binding()  {
        
        dataObservable.withUnretained(self).subscribe { own,_ in
            own.collectionView.reloadData()
        }.disposed(by: rx.disposeBag)
        
        
        activity_indicator.drive(collectionView.refreshControl!.rx.isRefreshing).disposed(by: rx.disposeBag)
        
        collectionView.refreshControl?.rx.controlEvent(.valueChanged).withUnretained(self).subscribe(onNext: { arg in
            arg.0.request()
        }).disposed(by: rx.disposeBag)
        
        
        NotificationCenter.default.rx.notification(.onClickShareMyApp, object: nil).withUnretained(self).subscribe(onNext: { own,_ in
        
            own.report_shared()
            
        }).disposed(by: rx.disposeBag)
        
        
        
    }
    
    
    fileprivate let activity_indicator = ST_ActivityIndicator()
    
    fileprivate let dataObservable = BehaviorRelay<[SectionModel<ST_TianDailyTaskSectionType,ST_TianDailyTaskCellModel>]>(value: [])
    
    fileprivate var data_array:[SectionModel<ST_TianDailyTaskSectionType,ST_TianDailyTaskCellModel>]{
        return dataObservable.value
    }
    
    deinit {
        self.dailyTaskAskRefresh.onNext(())
    }
    
    
    let dailyTaskAskRefresh = PublishSubject<Void>()
    
    // MARK: UICollectionViewDataSource
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data_array.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array[safe: section]?.items.count ?? 0
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_TianDailyTaskCell.self, for: indexPath)
        
        cell.model = data_array[safe: indexPath.section]?.items[safe: indexPath.item]
        
        return cell
        
    }
    
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        guard let section = data_array[safe: indexPath.section] else{
            return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_TianDailyTaskSectionReusableView.self, for: indexPath)
        }
        
        switch section.model {
            
        case .bannerHeader(let value,let banner):
            
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_TianDailyTaskBannerSectionReusableView.self, for: indexPath)
            
            view.bind(title: value, banner: banner)
            
            return view
            
        case .normalHeader(let value):
            
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_TianDailyTaskSectionReusableView.self, for: indexPath)
            
            view.titleStr = value
            
            return view
        }
    }
    
    
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        guard let item = data_array[safe: indexPath.section]?.items[safe: indexPath.item] ,let cell = collectionView.cellForItem(at: indexPath) as? ST_TianDailyTaskCell else{
            return
        }
        
        switch item.missionState {
        case .undone:
            print("每日任务动作🆔=",item.actionId)
            jumpBy(actionId: item.actionId)
        case .done:
            receiveEvent(rewardId: item.id.string, indexPath: indexPath, cell: cell)
        case .received:
            self.toast(text: "您今日已领取过啦~~")
        }
    }
    
}

extension ST_TianDailyTaskController:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        guard let item = data_array[safe:section]?.model else {
            return .zero
        }
        switch item {
        case .bannerHeader:
            return CGSize(width: ScreenWidth, height: 30+20+ScreenWidth/375.0*80)
        default:
            return CGSize(width: ScreenWidth, height: 30+20)
        }
    }
    
}

extension ST_TianDailyTaskController{
    
    @objc private func push_challenge_controller(){
        
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
            
                own.navigationController?.pushViewController(ST_TianChallengeController(), animated: true)
            
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    ///跳转 actionId 根据后台配置
    private func jumpBy(actionId:Int){
        
        switch actionId{
        case 1,112:
            self.navigationController?.pushViewController(ST_EditMyInfoViewController(), animated: true)
        case 3,102:
            push_challenge_controller()
        case 7,108:
            ST_MobilePhoneStepDispatcher.shared.start_phone_number(state: MobilePhoneNumberViewStep.bind, controller: self)
        case 8,109:
            DetectFaceHandle()
        case 9,110:
            push_to_push_peculiarity_controller(navigationController: self.navigationController)
        case 10,113:
            self.navigationController?.pushViewController(ST_MyPhotoViewController())
        case 115:
            
            ST_LaunchChargeWidget.shared.push_first_charge()
            
        case 11,114,111:
            self.navigationController?.popViewController(animated: true, {
                ST_BTLaunchController.shared.scroll_to_page(tab: .square)
            })
        case 4,12, 17,105,118:
            self.navigationController?.popViewController(animated: true, {
                ST_BTLaunchController.shared.scroll_to_page(tab: .msg)
            })
        case 5,6,13, 14, 15, 16,119,120,106,107:
            self.navigationController?.popViewController(animated: true, {
                ST_BTLaunchController.shared.scroll_to_page(tab: .room)
            })
        case 116:
            self.navigationController?.popViewController(animated: true, {
                ST_BTLaunchController.shared.scroll_to_page(tab: .recommend)
                ST_BTLaunchController.shared.home_controller.scroll_to_tab(index: 1)
            })
        case 117,103,104:
            self.navigationController?.popViewController(animated: true, {
                ST_BTLaunchController.shared.scroll_to_page(tab: .recommend)
            })
            break
        default:
            break
        }
        
    }
    
    /// 完成任务之后，领取红包
    fileprivate func receiveEvent(rewardId:String,indexPath:IndexPath,cell:ST_TianDailyTaskCell){
        
        cell.requestLoading()
        
        TIANSession(requestUrl: PH.receiveRewardsApi,parameters: ["award_id":rewardId]).withUnretained(self).subscribe{ own , result in
            
            cell.requestLoading(value: false)
            
            switch result {
            case .success:
                own.data_array[safe:indexPath.section]?.items[safe: indexPath.item]?.missionState = .received
                
                own.dataObservable.accept(own.data_array)
                
                own.toast(text: "领取成功啦~")
                
            case .failure(let err):
                own.toast(text: err.e)
            }
            
        }.disposed(by: rx.disposeBag)
        
        
    }
    
}

extension ST_TianDailyTaskController{
    
    fileprivate func request(){
        
        
        Observable.zip(TIANSession(requestUrl: PH.fetchDailyRewardsApi,parameters: ["type":1]), TIANSession(requestUrl: PH.fetchDailyRewardsApi,parameters: ["type":2])).track_activity(activity_indicator).withUnretained(self).subscribe { (own, arg) in
            
            var array = [SectionModel<ST_TianDailyTaskSectionType,ST_TianDailyTaskCellModel>]()
            
            if let array0 = own.wrapper(res: arg.0){
                
                array.append(SectionModel<ST_TianDailyTaskSectionType,ST_TianDailyTaskCellModel>(model: own.bannerModelGenerater(firstSection: array.count == 0, taskType: .新手任务), items: array0))
            }
            
            if let array1 = own.wrapper(res: arg.1){
                
                array.append(SectionModel<ST_TianDailyTaskSectionType,ST_TianDailyTaskCellModel>(model: own.bannerModelGenerater(firstSection: array.count == 0, taskType: .日常任务), items: array1))
            }
            
            own.dataObservable.accept(array)
            
        }.disposed(by: rx.disposeBag)
        
    }
    
    
    fileprivate func report_shared(){
        
        TIANSession(requestUrl: PH.reportSharedApi).withUnretained(self).subscribe(onNext: { own,result in
            
            switch result {
            case .success:
                own.request()
            case .failure:
                break
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    fileprivate func wrapper(res:Result<JSON,ST_NetworkError>)->[ST_TianDailyTaskCellModel]?{
        
        switch res {
        case .success(let json):
            
            print("大生意:",json)
            
            if let list = json["data"].array,list.count > 0{
                return list.map{ ST_TianDailyTaskCellModel(fromJson: $0) }
            }
            return nil
        case .failure:
            return nil
        }
    }
    
    fileprivate func bannerModelGenerater(firstSection:Bool,taskType:ST_TianDailyTaskType)->ST_TianDailyTaskSectionType{
        
        
        if firstSection && Defaults[.isPanda] == false && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female , let banner = SCComponets.rich_text_storage_component.json["ai_my_center"]["challenge_icon_big"].string,banner.count > 2{
            
            return .bannerHeader(value: taskType.rawValue, banner: banner)
            
        }else{
            return .normalHeader(value: taskType.rawValue)
        }
    }
    
}


extension ST_TianDailyTaskController{
    
    
    static func generator()->ST_TianDailyTaskController{
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize(width: ScreenWidth - 15*2, height: 68)
        
        layout.minimumLineSpacing = 15
        
        layout.minimumInteritemSpacing = 20
        
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 10, right: 15)
        
        layout.headerReferenceSize = CGSize(width: ScreenWidth, height: 30+20)
        
        return ST_TianDailyTaskController(collectionViewLayout: layout)
    }
}

private enum ST_TianDailyTaskType:String{
    case 新手任务 = "新手任务"
    case 日常任务 = "日常任务"
}

enum ST_TianDailyTaskSectionType {
    case normalHeader(value:String)
    case bannerHeader(value:String,banner:String)
}
